package fr.labri.macchiato.ui.preferences;

import java.util.ArrayList;
import java.util.List;

import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.HeaderItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.layout.VLayout;

import fr.labri.macchiato.core.model.UserPreferences;
import fr.labri.macchiato.core.model.utils.Day;
import fr.labri.macchiato.core.model.utils.TimeOfDay;
import fr.labri.macchiato.core.model.utils.TimeSlot;

/**
 * 
 * Widget to fill the preferences in terms of hours of shopping
 * 
 * @author Michelle AVOMO
 * @author Matthieu FOUCAULT
 */
public final class HoursWidget extends VLayout implements PreferencesWidget {

	private static final String DEFAULT_VALUE = "Renseignement de vos disponibilites pour les courses";

	private static final String WIDGET_TITLE = "Mes horaires de courses";

	private DynamicForm formHours;

	private TextItem startTimeItem;
	private TextItem endTimeItem;

	/**
	 * Public constructor
	 */
	public HoursWidget() {

		HeaderItem header = new HeaderItem();
		header.setDefaultValue(DEFAULT_VALUE);
		formHours = new DynamicForm();
		startTimeItem = new TextItem("Debut");
		endTimeItem = new TextItem("Fin");
		startTimeItem.setMask("00:00");
		endTimeItem.setMask("00:00");

		formHours.setTitle(WIDGET_TITLE);

		formHours.setFields(header, startTimeItem, endTimeItem);
		addMember(formHours);
	}

	/************************************ PRIVATE METHODS *******************************************/

	/**
	 * Gets the user's preference shopping hour
	 */

	public void collectUserPreferences(UserPreferences preference) {
		if (startTimeItem.getValue() != null && endTimeItem.getValue() != null) {

			TimeOfDay startTime = new TimeOfDay(
					startTimeItem.getValueAsString());
			TimeOfDay endTime = new TimeOfDay(endTimeItem.getValueAsString());

			TimeSlot time = new TimeSlot(Day.MONDAY, Day.SUNDAY, startTime,
					endTime);
			List<TimeSlot> timeSlot = new ArrayList<TimeSlot>();
			timeSlot.add(time);

			preference.setShoppingHours(timeSlot);
		}
	}

	/**
	 * Submits the form for validation
	 */
	public Boolean isValid() {
		return formHours.validate();
	}

	/**
	 * Gets the user preferences about giving a preference for his shopping hour
	 */
	public void restoreUserPreferences(UserPreferences preferences) {
		if (preferences.getShoppingHours() != null
				&& !preferences.getShoppingHours().isEmpty()) {
			startTimeItem.setValue(preferences.getShoppingHours().get(0)
					.getStartHour());
			endTimeItem.setValue(preferences.getShoppingHours().get(0)
					.getEndHour());
		}
	}

	/**
	 * Adds the widget to the current window
	 */
	public void addToParent(Window preference) {
		preference.addItem(this);

	}

	@Override
	public String getTitle() {
		return WIDGET_TITLE;
	}
}
